<?php
declare (strict_types=1);

namespace app\model;

use think\Model;

/**
 * @property int $gid 用户群组
 * @property int $leave 等级
 * @property int $status 用户状态
 * @property int $uid 用户编号
 * @property mixed $money 用户货币
 * @property string $create_ip 创建ip
 * @property string $create_time 创建时间
 * @property string $email 用户邮箱
 * @property string $guid 用户唯一标识
 * @property string $headimgurl 用户头像
 * @property string $idcard 身份证号
 * @property string $mobile 手机号
 * @property string $password 用户密码
 * @property string $update_ip 更新ip
 * @property string $update_time 更新时间
 * @property string $username 用户名
 * @property-read \app\model\MemberUserProfile $profile
 * @mixin \think\Model
 */
class MemberUser extends Model
{
    protected $pk = 'uid';


    public function profile()
    {
        return $this->hasOne(MemberUserProfile::class, 'uid');
    }


    /**
     * 用户登陆
     * @param $username
     * @param $password
     * @return MemberUser|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function login($username, $password)
    {
        $where = [
            ['email|username', "like", $username],
            ['password', "like", md5($password)],
        ];
        $user = self::where('email|username', "like", $username)->cache(true, 7200)->find();
        if (empty($user)) {
            return ['status' => -1];
        }
        if ($user->password != md5($password)) {
            return ['status' => -2];
        }
        $user->update_ip = request()->ip();
        $user->save();

        //格式化用户登陆
        $user = $user->toArray();
        unset($user['password']);
        return $user;
    }


    /**
     * 账号注册
     * @param string $email
     * @param string $password
     * @return MemberUser|Model
     * @author An Yang
     * @time 2020/8/6 11:29
     */
    public static function signUp(string $email, string $password)
    {

        $db = self::where("email", 'like', $email)->find();
        if (!empty($db)) {
            return $db;
        }
        $data = [
            'email' => $email,
            'password' => md5($password),
            'create_ip' => request()->ip(),
            'update_ip' => request()->ip(),
            'status' => 1,
        ];
        return self::create($data);
    }


}
